package com.fyy.netty.chapter01.c1;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Author fyy
 * @Description ByteBuffer分散读，集中写
 * @Date 2021/4/20 16:05
 */
public class ByteBufferReadWrite {

    public static void ScatteringReads(String filePath){
        try (RandomAccessFile file = new RandomAccessFile(filePath,"rw")){
            FileChannel channel = file.getChannel();
            ByteBuffer buffer1 = ByteBuffer.allocate(10);
            ByteBuffer buffer2 = ByteBuffer.allocate(10);
            ByteBuffer buffer3 = ByteBuffer.allocate(10);
            channel.read(new ByteBuffer[]{buffer1,buffer2,buffer3});
            buffer1.flip();
            buffer2.flip();
            buffer3.flip();
            System.out.println((char) buffer1.get());
            System.out.println((char) buffer2.get());
            System.out.println((char) buffer3.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void GatheringReads(String filePath){
        try (FileChannel channel = new RandomAccessFile(filePath, "rw").getChannel()) {
            ByteBuffer buffer = StandardCharsets.UTF_8.encode("你好");
            ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("李焕英");
            channel.write(new ByteBuffer[]{buffer,buffer1});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String filePath = "F:\\test.txt";
//        ScatteringReads(filePath);
        GatheringReads(filePath);
    }

}
